
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-03-07 14:39:20                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： SysSafeHostAddressService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using BestTrader.Cms.Models;
using Microsoft.AspNetCore.Http;

namespace BestTrader.Cms.Services
{
    public class SysSafeHostAddressService: ISysSafeHostAddressService
    {
        private const string COOKIES_ROLE3 = "COOKIES_ROLE3";
        private readonly ISysSafeHostAddressRepository _repository;

        public SysSafeHostAddressService(ISysSafeHostAddressRepository repository)
        {
            _repository = repository;
        }

        public bool AddAuthCookie(HttpContext context, string RoleId)
        {
            var result = true;
            if (RoleId == "1" || RoleId == "2")
            {
                context.SetCookies(COOKIES_ROLE3, COOKIES_ROLE3, 4000000);
                var entity = _repository.Get($"select * from SysSafeHostAddress where HostName='{ COOKIES_ROLE3 }' and RoleId=3");
                if (entity == null)
                {
                    // 添加未授权登录记录
                    entity = new SysSafeHostAddress
                    {
                        RoleId = 3,
                        HostName = COOKIES_ROLE3,
                        State = 0
                    };
                    result = _repository.Insert(entity) > 0;
                }
            }

            return result;
        }

        /// <summary>
        /// 授权只针对
        /// </summary>
        /// <param name="hostName"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public bool IsAuthorization(HttpContext context, string roleId)
        {
            if (roleId == "3")
            {
                var cookie = context.GetCookiesValue(COOKIES_ROLE3);
                if (cookie.IsNullOrWhiteSpace())
                {
                    return false;
                }
                var entity = _repository.Get($"select * from SysSafeHostAddress where HostName ='{ cookie }' and RoleId={ roleId } and State = 1");
                return entity != null;
            }

            return true;
        }
    }
}